package com.hyfd.task;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.namespace.QName;
import javax.xml.rpc.encoding.XMLType;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.message.SOAPHeaderElement;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.hyfd.common.utils.MD5;
import com.hyfd.common.utils.XmlUtils;
import com.hyfd.dao.mp.OrderDao;
import com.hyfd.dao.mp.ProviderPhysicalChannelDao;
import com.hyfd.rabbitMq.RabbitMqProducer;
import com.hyfd.rabbitMq.SerializeUtil;

@Component
public class MeiKeTask {
	
	Logger log = Logger.getLogger(getClass());
	@Autowired
	ProviderPhysicalChannelDao providerPhysicalChannelDao;
	@Autowired
	OrderDao orderDao;
	@Autowired
	RabbitMqProducer mqProducer;//消息队列生产者
	
//	@Scheduled(fixedDelay = 60000)
	public void queryMeiKeOrder(){
		Map<String,Object> map = new HashMap<String,Object>();
		int flag = 2;//充值中
		try{
			String providerPhysicalChannelId = "0000000051";//物理通道ID
			Map<String,Object> channel = providerPhysicalChannelDao.selectByPrimaryKey(providerPhysicalChannelId);//获取通道的数据
			String linkUrl = channel.get("link_url")+"";
			String defaultParameter = (String) channel.get("default_parameter");//默认参数
			Map<String,String> paramMap = XmlUtils.readXmlToMap(defaultParameter);
			String SOAPURI = paramMap.get("SOAPURI");//链结地址
			String Userid = paramMap.get("Userid");//用户编号
			String Uname = paramMap.get("Uname");//用户名
			String Password = paramMap.get("Password");//密码
	         //服务端url
            String endpointURL = linkUrl;
            Map<String,Object> param = new HashMap<String,Object>();
            param.put("dispatcherProviderId", providerPhysicalChannelId);
			param.put("status", "1");
			List<Map<String,Object>> orderList = orderDao.selectByTask(param);
			for(int i = 0 , size = orderList.size() ; i < size ; i++){
				Map<String,Object> order = orderList.get(i);
				String orderId = order.get("orderId")+"";
				map.put("orderId", orderId);
				String providerOrderId = order.get("providerOrderId")+"";
				String result = getOrderStatus(endpointURL,SOAPURI,Uname,Password,Userid,providerOrderId);
				Map<String, String> resultMap = readXml(result);
				String state = resultMap.get("state");
				String reason = resultMap.get("reason");
				map.put("resultCode", state+":"+reason);
				if(state.equals("7777")){
					flag = 1;
				}else if(state.equals("8888")){
					continue;
				}else{
					flag = 0;
				}
				map.put("status", flag);
				mqProducer.sendDataToQueue(RabbitMqProducer.Result_QueueKey, SerializeUtil.getStrFromObj(map));
			}
		}catch(Exception e){
			log.error("美科查询出错"+e);
		}
	}
	
	public String getOrderStatus(String endpointURL,String SOAPURI,String Uname,String Password,String Userid,String orderId){
		String result = null;
		try{
			Service service = new Service();
	        Call call = (Call) service.createCall();   
	        call.setTargetEndpointAddress(new java.net.URL(endpointURL));   
	        call.setSOAPActionURI(SOAPURI + "getMyOrderState");//要调用方法的url
	        call.setOperationName(new QName(SOAPURI, "getMyOrderState"));// 设置操作的名称。   
	        
	        //设置头信息
	        SOAPHeaderElement soapHeaderElement = new SOAPHeaderElement(SOAPURI, "MySoapHeader");   
	        soapHeaderElement.setNamespaceURI(SOAPURI);
	    	//设置头信息里需要的3个参数
	        soapHeaderElement.addChildElement("Uname").setValue(Uname);   
	        soapHeaderElement.addChildElement("Password").setValue(MD5.ToMD5(Password));
	        soapHeaderElement.addChildElement("Userid").setValue(Userid);
	        call.addHeader(soapHeaderElement);
	        call.setReturnType(XMLType.XSD_STRING);// 返回的数据类型 
	        call.addParameter(new QName(SOAPURI,"orderStr"), 
	                org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN);
	        result = (String) call.invoke(new Object[] {orderId});
		}catch(Exception e){
			log.error("美科查询方法出错"+e);
		}
		return result;
	}
	
	public static Map<String, String> readXml(String xml) {
		Document doc = null;
		Map<String, String> map = new HashMap<String, String>();
		try {
			doc = DocumentHelper.parseText(xml); // 将字符串转为XML
			Element rootElt = doc.getRootElement(); // 获取根节点
			String status = rootElt.elementTextTrim("status");
			String msg = rootElt.elementTextTrim("msg");
			map.put("status", status);
			map.put("msg", msg);
			Element data = rootElt.element("data");
			Element datalist = data.element("datalist");
			Element charged = datalist.element("charged");
			String state = charged.elementTextTrim("state");
			String reason = charged.elementTextTrim("reason");
			map.put("state", state);
			map.put("reason", reason);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
	
}
